<?php
class ArticleStats extends SpecialPage {

	var $ptitle;

	function __construct() {
		parent::__construct( 'ArticleStats' );
		wfLoadExtensionMessages( 'ArticleStats' );
		require_once( 'WikiContribsChart.php' );
	}

	function execute( $par ) {
		global $wgRequest, $wgOut, $wgMessageCache, $wgHttp, $wgScriptPath, $wgJpImgDir;

		// setup SpecialPage
		$this->setHeaders();

		// set article title
		if( isset( $par ) ) {
			$target = $par;
		} else {	
			$target = $wgRequest->getVal( 'target' );
		}			
		
		$this->set_article_title( $target );

		// output article search form
		$wgOut->addHTML( $this->getForm( '' ));

		// output stats table
		$wgOut->addHTML( "<style>table#article-stats { width:100%;margin:auto;border:solid 1px #000000; } #article-stats th, #article-stats td { border-bottom: solid 1px #545454; border-right: solid 1px #545454; padding:.5em; text-align:left; width: 25%; }</style>" );
		$wgOut->addHTML( "<table id='article-stats' cellspacing='0'><tr><th colspan='4' style='text-align:center;font-size:125%;border-bottom: solid 2px #545454;'>Article statistics &mdash; " . $this->get_article_title( false ) . "</th></tr>" ); 
		$wgOut->addHTML( "<tr><th>Number of edits:</th><td>" . $this->num_article_edits() . "</td>" );
		$wgOut->addHTML( "<th>Number of minor edits:</th><td>" . $this->num_minor_edits() . "</td></tr>" );
		$wgOut->addHTML( "<tr><th>First edit:</th><td>" . $this->first_edit( 'user' ) . " - " . $this->first_edit( 'timestamp' ) . "</td>" );
		$wgOut->addHTML( "<th>Most recent edit:</th><td>" . $this->most_recent_edit( 'user' ) . " - " . $this->most_recent_edit( 'timestamp' ) . "</td></tr>" );
		$wgOut->addHTML( "</table>" );

		$editsbyyear = $this->getEditsByYear();
		$graph = new WikiContribsChart( $this->get_article_title( false ), $editsbyyear );
		$graphimg = $graph->saveGraph( $this->get_article_title( true ) );
		$wgOut->addHTML( "<img src='" . $wgJpImgDir . $this->get_article_title( true ) . "-bargraph.png' />" ); 

	}

	public function set_article_title( $target ) {
		$this->ptitle = str_replace( " ", "_", $target );
	}

	public function get_article_title( $underscore=false ) {
		if ( isset( $this->ptitle ) ) {
			if( $underscore ) {
				return $this->ptitle;
			} else {
				return str_replace( "_", " ", $this->ptitle );
			}
		} else {
			$errormsg = 'Invalid page title';
			return $errormsg;
		}
	}

	public function num_article_edits() {
		$dbr = &wfGetDB( DB_SLAVE );
                $sql = "SELECT COUNT(*) as numedits, page.page_id, page.page_title, revision.rev_page, revision.rev_user, revision.rev_timestamp, revision.rev_user_text FROM page, revision WHERE page.page_id = revision.rev_page AND page.page_title = '" . $this->get_article_title( false ) . "' GROUP BY page.page_title";
                $res = $dbr->query( $sql );
		
		while ( $row = $dbr->fetchObject( $res ) ) {
			$numedits = $row->numedits;
		} 
		return $numedits;
	}	

	public function num_minor_edits() {
		$dbr = &wfGetDB( DB_SLAVE );
		$sql = "SELECT COUNT(*) as num_minor_edits, page.page_id, page.page_title, revision.rev_page, revision.rev_user, revision.rev_timestamp, revision.rev_user_text, revision.rev_minor_edit FROM page, revision WHERE page.page_id = revision.rev_page AND page.page_title = '" . $this->get_article_title( false ) . "'  AND revision.rev_minor_edit = 1 GROUP BY page.page_title;";
		$res = $dbr->query( $sql );
		if ( ! $dbr->numRows( $res ) > 0 ) {	
			return 0;
		}
		while ( $row = $dbr->fetchObject( $res ) ) {
			$minoredits = $row->num_minor_edits;
		}
		return $minoredits;
	}

	public function first_edit( $par = false ) {
		$dbr = &wfGetDB( DB_SLAVE );
		if ( ! $res ) {
			$sql = "SELECT DISTINCT page.page_id, page.page_title, revision.rev_page, revision.rev_user, revision.rev_timestamp, revision.rev_user_text FROM page, revision WHERE page.page_id = revision.rev_page AND page.page_title = '" . $this->get_article_title( false ) . "' ORDER BY revision.rev_timestamp LIMIT 1;";
			$res = $dbr->query( $sql );
			while ( $row = $dbr->fetchObject( $res ) ) {
				$first_edit_user = $row->rev_user_text;
				$first_edit_timestamp = $row->rev_timestamp;
			}
		}
		if ( $par == 'user' ) {
			return $first_edit_user;
		} elseif ( $par == 'timestamp' ) {
			return $first_edit_timestamp;
		} 
		
		$first_edit = array( $first_edit_user, $first_edit_timestamp );
		return $first_edit;
	}

        public function most_recent_edit( $par = false ) {
                $dbr = &wfGetDB( DB_SLAVE );
                if ( ! $res ) {
                        $sql = "SELECT DISTINCT page.page_id, page.page_title, revision.rev_page, revision.rev_user, revision.rev_timestamp, revision.rev_user_text FROM page, revision WHERE page.page_id = revision.rev_page AND page.page_title = '" . $this->get_article_title( false ) . "' ORDER BY revision.rev_timestamp DESC LIMIT 1;";
                        $res = $dbr->query( $sql );
                        while ( $row = $dbr->fetchObject( $res ) ) {
                                $recent_edit_user = $row->rev_user_text;
                                $recent_edit_timestamp = $row->rev_timestamp;
                        }
                }
                if ( $par == 'user' ) {
                        return $recent_edit_user;
                } elseif ( $par == 'timestamp' ) {
                        return $recent_edit_timestamp;
                }

                $recent_edit = array( $recent_edit_user, $recent_edit_timestamp );
                return $recent_edit;
        }	

	public function getEditsByYear() {
		$dbr = &wfGetDB( DB_SLAVE );
		$sql = "SELECT DISTINCT DATE_FORMAT(revision.rev_timestamp, '%Y') as year, COUNT( DATE_FORMAT( revision.rev_timestamp, '%Y' ) ) as yearcount FROM revision LEFT JOIN page ON page.page_id WHERE page.page_id = revision.rev_page AND page.page_title = '" . $this->get_article_title( false ) . "' GROUP BY year ORDER BY revision.rev_timestamp;";
		$res = $dbr->query( $sql );
		$i = 0;
		while ( $row = $dbr->fetchObject( $res ) ) {
			$years[$i] = $row->year;
			$yearcnt[$i] = $row->yearcount;
			$i++;
		}
		$editsbyyear = array( $years, $yearcnt );
		return $editsbyyear;
	}

	/**
	 * Generates the namespace selector form with hidden attributes.
	 * @param $this->opts Array: the options to be included.
	 */
	protected function getForm() {
		global $wgScript, $wgTitle;
	
		$this->opts['title'] = $wgTitle->getPrefixedText();

		if( !isset( $this->opts['target'] ) ) {
			$this->opts['target'] = '';
		} else {
			$this->opts['target'] = str_replace( '_' , ' ' , $this->opts['target'] );
		}
		
		$f = Xml::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript ) );
	
		foreach ( $this->opts as $name => $value ) {
			if( in_array( $name, array( 'namespace', 'target', 'contribs', 'year', 'month' ) ) ) {
				continue;
			}
			$f .= "\t" . Xml::hidden( $name, $value ) . "\n";
		}
	
		$f .= '<fieldset><br/>' .
			Xml::label( 'Article name: ') . ' '.
			Xml::input( 'target', 30, $this->opts['target']) . ' '.
			Xml::submitButton( wfMsg( 'sp-contributions-submit' ) ) . '</blockquote>';
	
		$explain = wfMsgExt( 'sp-contributions-explain', 'parseinline' );

		if( !wfEmptyMsg( 'sp-contributions-explain', $explain ) )
			$f .= "<p>{$explain}</p>";
	
		$f .= '</fieldset>' . Xml::closeElement( 'form' );

		return $f;
	}
}
